package com.example.fitapp.activity.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.fitapp.activity.R;
import com.example.fitapp.activity.adapter.ReadyRecycleAdapter;
import com.example.fitapp.activity.http.api.dynamic.CreateDynamic;
import com.example.fitapp.activity.http.api.dynamic.GetDynamicAll;
import com.example.fitapp.activity.http.api.dynamic.UploadImage;
import com.example.fitapp.activity.http.util.ApiListener;
import com.example.fitapp.activity.http.util.ApiUtil;
import com.example.fitapp.activity.http.util.ImagePost;
import com.example.fitapp.activity.http.util.OkHttpCallback;
import com.example.fitapp.activity.http.util.OkHttpUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PushActivity extends AppCompatActivity implements View.OnClickListener {

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    public static final  int TAKE_PHOTO = 1;
    public static final int CHOOSE_PHOTO = 2;

    private File file;
    private Uri imageUri;
    private String takePhotoPath;  // 拍照的路径
    private String alumPhotoPath;  // 相册路径
    private ReadyRecycleAdapter adapter;

    private List<String> putImageUrl = new ArrayList<String>();

    private List<ReadlyPushImage> readlyImage = new ArrayList<>();
    // 发布推送的变量
    private EditText editText;
    private String pushuTextContent;
    private String pushTitleContent;
    private EditText pushTitle;
    private ImageView open_alum;
    private ImageView take_photo;
    private RecyclerView recely_view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_push);
        editText = (EditText) findViewById(R.id.push_Text);
        pushTitle = (EditText) findViewById(R.id.push_Title);

         open_alum = (ImageView) findViewById(R.id.open_alum);
         take_photo = (ImageView) findViewById(R.id.take_photo);
        open_alum.setOnClickListener(this);
        take_photo.setOnClickListener(this);

        recely_view = (RecyclerView) findViewById(R.id.recely_view);
        StaggeredGridLayoutManager layoutManager  = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
        //layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recely_view.setLayoutManager(layoutManager);

        adapter = new ReadyRecycleAdapter(readlyImage);
        recely_view.setAdapter(adapter);

    }


    // 点击事件
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.open_alum){
            open_photo();
        }
        if (v.getId() == R.id.take_photo){
            takePhoto();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.push_option,menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.push_activity:
                pushuTextContent = editText.getText().toString(); // 获取文本内容
                pushTitleContent = pushTitle.getText().toString(); // 获取文本标题
                try {
                    pushuActivity(0,putImageUrl,pushuTextContent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
        return true;
    }
    // 拍照
    private  void takePhoto() {
        file = new File(getExternalCacheDir(),"output_image.png");
        try {
            Log.i("file",file.getAbsolutePath());
            if (file.exists()){
                file.delete();
            }
            file.createNewFile();
        }catch (IOException e){
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT >= 24){
            imageUri = FileProvider.getUriForFile(PushActivity.this,"com.example.fitapp.activity",file);
        }else {
            imageUri = Uri.fromFile(file);
        }
        takePhotoPath =file.toString();
        // 启动相机
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
        startActivityForResult(intent,TAKE_PHOTO);
    }

    // 打开相册
    private void open_photo() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO); // 打开相册
    }
    // post上传图片
    private void pushPhtot(String name, File file, final Bitmap bitmap) {
        RequestBody fileBody = RequestBody.create(MEDIA_TYPE_PNG, file);

        final RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file",file.getName(),fileBody)
                .addFormDataPart("name",name)
                .build();
        if (putImageUrl.size() == 6){
            Toast.makeText(PushActivity.this,"上传图片不能超过6张",Toast.LENGTH_LONG).show();
        }else {
            ImagePost.post("/v1/common/upload", requestBody, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.d("MainActivity","asda"+e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String stringdata = response.body().string();
                    String urlStr = null;
                    try {
                        urlStr =  new JSONObject(stringdata).getString("url");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    putImageUrl.add(urlStr);

                    readlyImage.add(new ReadlyPushImage(bitmap));

                    Log.d("ssss",""+  urlStr);

                    runOnUiThread(new Runnable() { // 通知适配器更新
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                        }
                    });

                }
            });

        }

    }



    // 成功回调 打开相册和拍照的
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK){
                    try {
                        file = new File(takePhotoPath);
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri)); // 用于展示
                        pushPhtot("take",file,bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK){
                    handleImageOnKitKat(data);
                }
                break;
            default:
                break;
        }
    }

    // 4.4以上的手机版本(不同手机版本的照片处理
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)){
            // 如果是document 类型的uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id =docId.split(":")[1]; // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contenUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                String ImagePath = getImagePath(contenUri, null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            imagePath = getImagePath(uri, null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            imagePath = uri.getPath();
        }
        File file = new File(imagePath);
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        pushPhtot("pushuPhoto",file,bitmap);
    }

    // 获取图片文件路径
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri 和 selection 来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
        if (cursor != null){
            if (cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path; // 返回真是的图片文件路径
    }

    // 发布动态的上传方式
    private void pushuActivity(int pushuPhotoLength,List data,String pushuTextData) throws JSONException {
        if (data == null || pushuTextData == null){
            return;
        }
        JSONArray jsonArray = null;
        jsonArray = new JSONArray(data);
        new CreateDynamic(pushTitleContent,pushuTextData,jsonArray.toString()).post(new ApiListener() {
            @Override
            public void success(ApiUtil apiUtil) {
                CreateDynamic api = (CreateDynamic)apiUtil;
                String response = api.mResponse;
                putImageUrl.clear();
                Log.i("发布成功",""+response);
                Intent intent = new Intent(PushActivity.this,MainActivityWithTap.class);
                startActivity(intent);
//                finish();
            }

            @Override
            public void failure(ApiUtil apiUtil) {
                Log.i("发布失败","" + apiUtil);
            }
        });

    }

}
